package com.panopset.sf.apps.blackjack;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JComponent;

import com.panopset.compat.MathUtil;
import com.panopset.compat.Strings;
import com.panopset.game.blackjack.BlackjackGame;
import com.panopset.sf.Windoc;
import com.panopset.sf.WindocField;
import com.panopset.sf.apps.PanopsetApp;

/**
 * Panopset Blackjack, the Swingframe version.
 *
 * @author Karl Dinwiddie
 *
 */
public class Blackjack extends PanopsetApp {

    /**
     * @param args
     *            Not used.
     */
    public static void main(final String... args) {
        new Blackjack().show();
    }

    @Override
    public JComponent createPanel(final Windoc w) {
        BlackjackSwingConfig config = new BlackjackSwingConfig(w);
        final BlackjackGame m = new BlackjackGame(config);
        new WindocField(w, "0", "HighScore") {

            @Override
            protected String getGuiValue() {
                return "" + m.getGoofy().getHandsSinceLastMistakeRecord();
            }

            @Override
            protected void setGuiValue(String value) {
                if (Strings.isPopulated(value)) {
                    try {
                        m.getGoofy().setHandsSinceLastMistakeRecord(
                                Integer.parseInt(value));
                    } catch (NumberFormatException ex) {
                        // nothing to do here.
                    }
                }
            }

        };
        final BlackjackSwingPanel bsp = new BlackjackSwingPanel(w, m,
                config.getPanel());
        final Felt f = bsp.getFelt();
        JComponent fc = f.getPanel();
        fc.setFocusable(true);
        fc.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(final KeyEvent e) {
                if (e.isControlDown() || e.isAltDown()) {
                    return;
                }
                if (bsp.getFrontPane().getSelectedComponent()
                        .equals(bsp.getFelt().getPanel())) {
                    m.exec(f.commander.findCommand(e.getKeyCode()).getAction());
                }
            }
        });
        m.setExecListener(f);
        return bsp.getPanel();
    }
}
